import fs from 'fs';
import path from 'path';
import { ResolverResultObject } from 'unplugin-auto-import/types';

import { PlatformSplitChar, walkSync } from './utils';
//  全局注册 hooks
//utils路径
const prefixHooksPath = path.resolve(process.cwd(), `src${PlatformSplitChar}hooks`);

const primitiveHooksNames: { [key: string]: { as?: string; name?: string; from: string } } = {};

walkSync(prefixHooksPath, ['.ts', '.tsx'], function (p) {
  const fileContent = fs.readFileSync(p, { encoding: 'utf-8' });
  const targets =
    fileContent.match(/export(\s*)(function|const|type|interface|class)(\s*)(\w+)/gim) || [];
  targets.forEach((s) => {
    const names = s.split(' ');
    const targetName = names[names.length - 1];

    //绝对路径替换成别名路径
    let related = p.split(PlatformSplitChar).join('/');

    //移除文件后缀
    related = related.substring(0, related.lastIndexOf('.'));

    //如果有重名
    if (!primitiveHooksNames[targetName]) {
      primitiveHooksNames[targetName] = {
        as: targetName,
        from: `${related}`,
        name: targetName,
        // importName: targetName,
      };
    } else {
      //来自不同文件的重名，给出警告
      //来自同个文件就是重载，忽略
      if (primitiveHooksNames[targetName].from != related) {
        console.warn('命名冲突!', targetName + '    ------------->     ' + related);
      }
    }
  });
});

function isGllHook(name: string) {
  return Object.keys(primitiveHooksNames).includes(name);
}

// 本地hooks导入
export function GllHooksResolver(): ResolverResultObject {
  return {
    //无用
    type: 'component',
    resolve: (name) => {
      if (isGllHook(name)) return primitiveHooksNames[name];
    },
  };
}
